package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.R;
import com.example.reggie.entity.Employee;
import com.example.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 老肥！！！
 * @Date: 2022/09/05/20:28
 * @Description: 不想学代码了！！！
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R login(HttpServletRequest httpServletRequest, @RequestBody Employee employee){
//      将页面提交的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
//      根据用户提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lambdaQueryWrapper);
//        如果没有查询到就返回登陆失败结果
        if (emp == null){
            return  R.error("登录失败");
        }
//        密码对比如果不一致，则返回登陆失败结果
        if (!emp.getPassword().equals(password)){
            return  R.error("登陆失败");
        }
//        查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus()==0){
            return R.error("该员工已禁用");
        }
//        登录成功，将该员工id存入Session并返回登录成功结果
//       setAttribute方法描述: 比如访问一个网站，登录后用户信息被保存到session中，在session过期之前或者用户关闭页面之前，用
//        户信息可以通过request.getSession().getAttribute()方式获得。
        httpServletRequest.getSession().setAttribute("employee",emp.getId());
        return  R.success(emp);
    }
    @PostMapping("/logout")
    public R logout(HttpServletRequest httpServletRequest){
//        清理Session中保存的当前登录员工的id
        httpServletRequest.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("employee:"+ employee);
        //        设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        设置用户注册时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
//      获得当前用户的id（通过登录将用户的id存入session域中）
        long emp= (long)request.getSession().getAttribute("employee");
        employee.setCreateUser(emp);
        employee.setUpdateUser(emp);
        employeeService.save(employee);
        return  R.success("保存成功");
    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page = {},size = {},name = {}",page,pageSize,name);
//        添加分页构造器
        Page<Employee> employeePage = new Page<>(page,pageSize);
//        添加条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//        添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
//        添加排序查询
        queryWrapper.orderByDesc(Employee::getUpdateTime);
//        执行查询
        employeeService.page(employeePage,queryWrapper);
        return R.success(employeePage);
    }
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
            log.info(employee.toString());
            Long empID = (Long) request.getSession().getAttribute("employee");
            employee.setUpdateTime(LocalDateTime.now());
            employee.setUpdateUser(empID);
            employeeService.updateById(employee);

            return  R.success("员工信息修改成功");
    }
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到该员工信息");
    }
}
